package neu.soft.service.impl;

import com.alibaba.fastjson.JSONObject;
import neu.soft.constant.OrderStatus;
import neu.soft.constant.TaskOrderStatus;
import neu.soft.constant.TaskOrderType;
import neu.soft.entity.DistributionTaskOrder;
import neu.soft.entity.NormalOrder;
import neu.soft.feignclient.DispatchFeignClient;
import neu.soft.feignclient.UserFeignClient;
import neu.soft.mapper.TaskOrderMapper;
import neu.soft.producer.ProduceService;
import neu.soft.service.TaskOrderService;
import neu.soft.vo.PageBean;
import neu.soft.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaskOrderServiceImpl implements TaskOrderService {


    @Autowired
    private TaskOrderMapper taskOrderMapper;

    @Autowired
    private DispatchFeignClient dispatchFeignClient;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProduceService produceService;


    public ResultBean<DistributionTaskOrder> findById(String id) {

        ResultBean<DistributionTaskOrder> res = new ResultBean<>();

        DistributionTaskOrder distributionTaskOrders = taskOrderMapper.findById(id);


        res = res.success(distributionTaskOrders);

        return res;
    }

    public ResultBean<PageBean<DistributionTaskOrder>> findByConditions(Map<String, Object> map){

        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        Date date = null;
        try {
            if (!"".equals((String) map.get("date")) && map.get("date") != null) {
                date = simpleDateFormat.parse((String) map.get("date"));
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        // 将 任务类型 和 任务状态 设置为枚举类型。用数字0~6代表各种状态，数字0~4代表各种类型
        // 根据数字获取所代表的文字含义
        TaskOrderType type = TaskOrderType.getItem(map.get("type").toString()) ;
        TaskOrderStatus status = TaskOrderStatus.getItem(map.get("status").toString()) ;

        // get到map中的各种数据
        int pageNow = (int) map.get("pageNow");
        int pageSize = (int) map.get("pageSize");
        int isReceipt = (int) map.get("isReceipt");
        String id = (String) map.get("distributionTaskOrderId");

        ResultBean<PageBean<DistributionTaskOrder>> res = new ResultBean<>();
        PageBean<DistributionTaskOrder> pageBean = new PageBean<>();
        Long totalRows;



        List<DistributionTaskOrder> distributionTaskOrders =new ArrayList<>();
        if (date == null) {
            // 进行分页查询，将各条件传入mapper
            distributionTaskOrders = taskOrderMapper.findByConditions((pageNow - 1) * pageSize, pageSize, null, type, status, null, id, isReceipt);
            // 获取数据总条数
            totalRows = taskOrderMapper.getTotalRows(null, type, status, null, id, isReceipt);
        }
        else {
            // 获取当前时间+1天的时间，用于比较时间，选择出今天任何时间段内的数据
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.DATE,1);
            Date date2 = calendar.getTime();

            totalRows = taskOrderMapper.getTotalRows(date, type, status, date2, id, isReceipt);
            distributionTaskOrders = taskOrderMapper.findByConditions((pageNow - 1) * pageSize, pageSize, date, type, status, date2, id, isReceipt);
        }

        if(distributionTaskOrders.size() == 0) {
            res = res.error();
        }else {
            pageBean.setRowData(distributionTaskOrders);
            pageBean.setTotalRows(totalRows);
            pageBean.setTotalPages((int) (totalRows % pageSize == 0 ? (totalRows/pageSize) : (totalRows/pageSize + 1)));
            res = res.success(pageBean);
        }

        return res;
    }

    public ResultBean<PageBean<DistributionTaskOrder>> findAll(Map<String , Object> map) {

        ResultBean<PageBean<DistributionTaskOrder>> res = new ResultBean<>();

        PageBean<DistributionTaskOrder> pageBean = new PageBean<>();

        int pageNow = (int) map.get("pageNow");
        int pageSize = (int) map.get("pageSize");

        System.out.println(pageNow);
        System.out.println(pageSize);

        List<DistributionTaskOrder> distributionTaskOrders = taskOrderMapper.findAll((pageNow - 1)* pageSize, pageSize);

        Long totalRows = taskOrderMapper.getTotalRows(null, null, null, null, null, 1);


        if(distributionTaskOrders.size() == 0) {
            res = res.error();
        }else {
            pageBean.setRowData(distributionTaskOrders);
            pageBean.setTotalRows(totalRows);
            pageBean.setTotalPages((int) (totalRows % pageSize == 0 ? (totalRows/pageSize) : (totalRows/pageSize + 1)));
            res = res.success(pageBean);
        }

        return res;

    }

    public ResultBean<List<DistributionTaskOrder>> findPostmanForOrder(String distributionTaskOrders) {

        System.out.println(distributionTaskOrders);

        // 将获取到的json类型的字符串转化为list对象
        List<DistributionTaskOrder> orders = new ArrayList<>();
        orders = JSONObject.parseArray(distributionTaskOrders,DistributionTaskOrder.class);


        // 遍历list，为每个配送单分配配送员
        for (DistributionTaskOrder order : orders) {
            // 调用mapper接口，获取当前配送单的配送员，并修改
            String id = taskOrderMapper.findRandomPostman(order.getAddressId());
            order.setPostmanId(id);
        }


        orders.forEach(System.out::println);

        // 调用mapper，传入配送单集合，进行修改
        int k=taskOrderMapper.updateOrders(orders);
        // 同时将配送单状态修改为“已分配”
        for (DistributionTaskOrder order : orders) {
            changeOrderStatus(3, order.getOrderId(), OrderStatus.Have_Distributed);
        }


        return null;
    }

    public void changeOrderStatus(int status, String oid, OrderStatus orderStatus) {
        Map<String, Object> map = new HashMap<>();
        map.put("oid", oid);
        map.put("status", orderStatus);
        userFeignClient.changeOrderStatus(map);
        map.replace("status", status);
        dispatchFeignClient.statusUpdate(map);
    }

    public void storeTaskOrders(List<Map<String, Object>> distributionTaskOrders) {
        for (Map<String, Object> distributionTaskOrder:
             distributionTaskOrders) {
            TaskOrderStatus taskOrderStatus = TaskOrderStatus.getItem(distributionTaskOrder.get("taskState").toString());
            distributionTaskOrder.replace("taskState", taskOrderStatus);
            TaskOrderType taskOrderType = TaskOrderType.getItem(distributionTaskOrder.get("taskType").toString());
            distributionTaskOrder.replace("taskType", taskOrderType);
            taskOrderMapper.storeTaskOrders(distributionTaskOrder);
        }
    }

    public ResultBean<Map<String, Object>> getPrintTaskOrder(String distributionOrderId, String orderId) {

        System.out.println(distributionOrderId+"1111"+orderId);

        // 根据oiderID获取订单信息
        ResultBean<Map<String, Object>> resultBean = dispatchFeignClient.findPrintOrder(orderId);
        Map<String, Object> data = resultBean.getData();

        // 根据did获取配送单信息
        DistributionTaskOrder distributionTaskOrder = findById(distributionOrderId).getData();

        // 将订单信息和部分配送单信息进行合并
        data.put("addressId", distributionTaskOrder.getAddressId());
        data.put("address",distributionTaskOrder.getAddress());
        data.put("distributionTaskOrderId",distributionTaskOrder.getDistributionTaskOrderId());
        data.put("customerName",distributionTaskOrder.getCustomerName());
        data.put("taskType",distributionTaskOrder.getTaskType());
        String goodsName = (String) data.get("shoppingName");
        String[] names = goodsName.split(",");
        String prices = (String) data.get("shoppingPrice");
        String[] ps = prices.split(",");
        String price = "";
        System.out.println(price);
        String nums = (String) data.get("shoppingNum");
        String[] ns = nums.split(",");
        String num = "";

        List<Map<String, Object>> list = new ArrayList<>();
        float totalPrice = 0;
        for (int i = 0;i < ps.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("goodName",names[i]);
            map.put("price", ps[i]);
            totalPrice += Float.parseFloat(ps[i]);
            map.put("goodCount", ns[i]);
            list.add(map);
        }
        data.put("list",list);
        data.put("totalPrice",totalPrice);
        System.out.println(data);
        ResultBean<Map<String, Object>> res = ResultBean.success(data);

        // 修改订单状态
        taskOrderMapper.updateOrderStatus(distributionOrderId);
        changeOrderStatus(4, orderId, OrderStatus.Picked_By_Deliveryman);
        List<String> list1 = new ArrayList<>();
        list1.add(orderId);
        System.out.println("******发送消息******");
        produceService.send(list1);
        return res;
    }


    public  ResultBean receiptEntry(Map<String, Object> map){

        // 修改配送单状态
        String state = (String) map.get("taskState");
        map.put("taskState", TaskOrderStatus.getItem(state));
        int k = taskOrderMapper.updateTaskById(map);

        // 如果回执状态为“失败”，需要重新发货
        if("失败".equals(state)) {
            String oid = (String) map.get("orderId");
            Map<String, Object> map1 = new HashMap<>();
//            map1.put("oid",oid);
//            map1.put("status",0);
//            dispatchFeignClient.statusUpdate(map1);
            changeOrderStatus(0,oid, OrderStatus.Ready_To_Distribute);
            NormalOrder normalOrder = new NormalOrder();
            normalOrder.setOid(oid);
            dispatchFeignClient.DistributionTaskOrder(normalOrder);
        }

        return null;
    }


}
